package com.monkeybrother.spring.async;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

@Service
public class AsyncService {

    private final ExecutorService executorService;

    @Autowired
    public AsyncService(@Qualifier("executorService") ExecutorService executorService) {
        this.executorService = executorService;
    }

    public String performAsyncOperation() {
        Future<String> future = executorService.submit(new AsyncCallable());
        System.out.println("当前时间：" + System.currentTimeMillis() + " 请求进来了...");
        try {
            String result = future.get();
            System.out.println("当前时间：" + System.currentTimeMillis() + " 异步获取到结果: " + result);
            return result;
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return "";
        }
    }
}
